package com.calendar.api.controller;

import com.calendar.api.model.ApiResponse;
import com.calendar.api.model.Category;
import com.calendar.api.model.dto.CategoryDTO;
import com.calendar.api.security.JwtTokenProvider;
import com.calendar.api.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/categories")
@Api(tags = "分类管理")
public class CategoryController {

    private final CategoryService categoryService;
    private final JwtTokenProvider jwtTokenProvider;

    @Autowired
    public CategoryController(CategoryService categoryService, JwtTokenProvider jwtTokenProvider) {
        this.categoryService = categoryService;
        this.jwtTokenProvider = jwtTokenProvider;
    }

    @GetMapping
    @ApiOperation("获取所有分类")
    public ApiResponse<List<Category>> getAllCategories(HttpServletRequest request) {
        String token = jwtTokenProvider.resolveToken(request);
        Long userId = jwtTokenProvider.getUserId(token);
        return ApiResponse.success(categoryService.getAllCategories(userId));
    }

    @GetMapping("/{id}")
    @ApiOperation("获取单个分类")
    public ApiResponse<Category> getCategory(@PathVariable Long id, HttpServletRequest request) {
        String token = jwtTokenProvider.resolveToken(request);
        Long userId = jwtTokenProvider.getUserId(token);
        return ApiResponse.success(categoryService.getCategory(id, userId));
    }

    @PostMapping
    @ApiOperation("创建分类")
    public ApiResponse<Category> createCategory(@Valid @RequestBody CategoryDTO categoryDTO, HttpServletRequest request) {
        String token = jwtTokenProvider.resolveToken(request);
        Long userId = jwtTokenProvider.getUserId(token);
        return ApiResponse.success(categoryService.createCategory(categoryDTO, userId));
    }

    @PutMapping("/{id}")
    @ApiOperation("更新分类")
    public ApiResponse<Category> updateCategory(@PathVariable Long id, @Valid @RequestBody CategoryDTO categoryDTO, HttpServletRequest request) {
        String token = jwtTokenProvider.resolveToken(request);
        Long userId = jwtTokenProvider.getUserId(token);
        return ApiResponse.success(categoryService.updateCategory(id, categoryDTO, userId));
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除分类")
    public ApiResponse<Void> deleteCategory(@PathVariable Long id, HttpServletRequest request) {
        String token = jwtTokenProvider.resolveToken(request);
        Long userId = jwtTokenProvider.getUserId(token);
        categoryService.deleteCategory(id, userId);
        return ApiResponse.success();
    }
} 